<?php
JunctionFileCabinet::using("Junction_Utils_Reflection_Facade");

/**
 * Represent a table in the database.
 *
 * <p>This class contains a list of scalar values which
 * are mapped by the user.  The values map between object 
 * properties and table columns.
 * <p>This class is used to facilitate reading of scalar
 * values for the user.  In addition this class is delegated
 * the task of constructing queries against it.
 */
class Junction_Mapping_Table {
	
	private $_name;
	
	/**
	 * @var array
	 */
	private $_properties;
	private $_columns;
	
	/**
	 * @var String a pointer into the properties
	 */
	private $_primaryKey;
	
	public function __construct($name) {
		$this->_name = $name;
		$this->_properties = array();
		$this->_columns = array();
	}
	
	/**
	 * @param String $property
	 * @return boolean
	 */
	public function contains($property) {
		return (isset($this->_properties[$property]));
	}
	
	/**
	 * @param String $property
	 * @return String
	 */
	public function propertyToColumn($property) {
		return $this->_properties[$property];
	}
	
	/**
	 * @param String $column
	 * @return String
	 */
	public function columnToProperty($column) {
		return $this->_columns[$column];
	}
	
	/***
	 * @return Iterator <property, column>
	 */
	public function getColumns() {
		return new ArrayIterator($this->_properties);
	}
	
	/**
	 * @return String property
	 */
	public function getPrimaryKey() {
		return $this->_primaryKey;
	}
	
	/**
	 * @param String $property
	 * @param String $column
	 */
	public function addColumn($property, $column) {
		$this->_properties[$property] = $column;
		$this->_columns[$column] = $property;
	}
	
	/**
	 * @param String $property
	 * @param String $column
	 */
	public function addKey($property, $column) {
		$this->_primaryKey = $property;
		$this->addColumn($property, $column);
	}
	
	/**
	 * @param Object $builder
	 * @return Junction_Query_Builder
	 */
	public function buildQuery(Junction_Query_Builder $builder, $object) {
		$builder->bindTable($this->_name);
		foreach ($this->getColumns() as $property => $column) {
			$value = null;
			if (isset($object)) {
				$value = Junction_Utils_Reflection_Facade::getValueFor($object, $property);
			}
			$builder->bindProperty($column, $value);
		}
		return $builder;
	}
}
?>